import { Injectable, Optional } from '@angular/core';
import { Base } from '../view/base';


@Injectable({
  providedIn: 'root'
})
export class DataGridPageJumpService<U, B, S> extends Base<U, B, S> {

  init(dataGrid: any) {
    const dataGridEle = dataGrid.instance.element();
    const pagerEle = dataGridEle.querySelector('.dx-pager');
    if (!pagerEle || dataGrid.__pageJump) {
      return;
    }

    const inputEle = this._initEle(pagerEle);
    dataGrid.onContentReady.subscribe(() => {
      inputEle.value = dataGrid.instance.pageIndex() + 1 + '';
    });

    inputEle.addEventListener('keypress', (e) => {
      if ((Number.isNaN(+e.key)) && e.key !== 'Enter') {
        e.stopPropagation();
        e.preventDefault();
      }

      if (e.key === 'Enter') {
        let pageNum = parseInt(inputEle.value, 10);
        if (Number.isNaN(pageNum) || pageNum === 0) {
          pageNum = 1;
          inputEle.value = pageNum.toString();
        }
        dataGrid.dataSource.pageIndex(pageNum - 1);
        dataGrid.dataSource.reload();
      }
    });
    dataGrid.__pageJump = true;
  }

  private _initEle(pagerEle: HTMLElement): HTMLInputElement {
    const pageJumpEle = document.createElement('div');
    const pagerEleStyles = window.getComputedStyle(pagerEle);
    const paddingRight = pagerEleStyles.getPropertyValue('padding-right');
    const paddingTop = pagerEleStyles.getPropertyValue('padding-top');
    pagerEle.style.paddingRight = `${parseInt(paddingRight, 10) + 140}px`;
    pageJumpEle.style.cssText = `
      position: absolute;
      bottom: 0;
      right: 0;
      padding-top: calc(${paddingTop} + 1px);
      padding-right: ${paddingRight};
      height: ${pagerEle.offsetHeight || 50}px;
    `;
    const leftTextEle = document.createElement('span');
    leftTextEle.textContent = this.i18nService.getValue('@go', 'core');
    const rightTextEle = document.createElement('span');
    rightTextEle.textContent = this.i18nService.getValue('@page', 'core');
    const inputEle = document.createElement('input');
    inputEle.className = 'ant-input';
    inputEle.style.cssText = `
      width: 5em;
      margin: 0 10px;
      text-align: center;
    `;
    pageJumpEle.appendChild(leftTextEle);
    pageJumpEle.appendChild(inputEle);
    pageJumpEle.appendChild(rightTextEle);
    pagerEle.parentElement.appendChild(pageJumpEle);

    return inputEle;
  }
}
